from fastapi import APIRouter, Depends, Form, HTTPException, Query  # UploadFile, File 已移除，云侧不再接收图像
from sqlalchemy.orm import Session
from db.connection import get_db
from services.conversation import ConversationService
# 人脸识别功能已注释，云侧不再进行人脸识别
# from services.face_recognition import FaceRecognitionService
from services.user import UserService
# from services.reflection import ReflectionService  # 反思模块已注释
# from services.llm import LLMService  # 未在routes中直接使用
from services.tasks import process_conversation_end  # , analyze_personality_after_message, analyze_emotion_after_message  # 未在routes中直接使用
# from utils.upload import upload_to_obs  # OBS服务已注释
from utils.logger import (
    emobot_logger,
    log_function_call,
    log_function_result,
    log_function_error,
)
from utils.performance_logger import (
    performance_tracker,
    track_step,
    log_api_call,
    log_data_transfer,
    log_database_operation,
    log_cache_operation
)
from typing import Optional, Dict, Any
import time
import json

from fastapi.responses import JSONResponse, StreamingResponse
# import numpy as np  # 未使用
# import cv2  # 未使用
# import insightface  # 人脸识别已注释
# from insightface.app import FaceAnalysis  # 人脸识别已注释
# import tempfile  # 未使用
from dotenv import load_dotenv
# from utils.image_path_manager import image_manager  # 图像处理已注释

load_dotenv()

logger = emobot_logger.get_logger()

router = APIRouter(prefix="/api/conversation", tags=["conversation"])


@router.post("/start")
def start_conversation(user_id: str = Form(...), db: Session = Depends(get_db)):
    """Start a new conversation"""
    start_time = time.time()
    log_function_call("start_conversation", {"user_id": user_id})
    emobot_logger.log_api_request(
        "POST", "/api/conversation/start", {"user_id": user_id}, user_id=user_id
    )

    try:
        # 支持访客模式：允许没有用户档案的用户开始对话
        user_service = UserService(db)
        user_profile = user_service.get_user_profile(user_id)
        is_guest_mode = user_profile is None
        
        if is_guest_mode:
            logger.info(f"User profile not found for user {user_id}, starting conversation in guest mode")

        conversation_service = ConversationService(db)
        session_id = conversation_service.start_conversation(user_id)

        result = {
            "session_id": session_id,
            "message": "Conversation started successfully",
        }
        duration = (time.time() - start_time) * 1000

        emobot_logger.log_api_response(
            "POST", "/api/conversation/start", 200, result, duration
        )
        emobot_logger.log_conversation_event("start", user_id, session_id)
        log_function_result("start_conversation", result, duration)

        return result
    except Exception as e:
        duration = (time.time() - start_time) * 1000
        log_function_error("start_conversation", e, {"user_id": user_id})
        emobot_logger.log_api_response(
            "POST", "/api/conversation/start", 500, {"error": str(e)}, duration
        )
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/interact")
async def interact(
        user_id: Optional[str] = Form(None),
        session_id: Optional[str] = Form(None),
        message: str = Form(...),
        plane_description: Optional[str] = Form(None),
        environment_summary: Optional[str] = Form(None),
        robot_id: Optional[str] = Form(None),
        # image: Optional[UploadFile] = File(None),  # 云侧不再接收图像数据
        db: Session = Depends(get_db),
):
    """Send a message in an existing conversation with face recognition"""
    # 开始性能追踪
    request_id = performance_tracker.start_request(
        user_id=user_id,
        session_id=session_id
    )

    start_time = time.time()
    log_function_call(
        "interact",
        {
            "user_id": user_id,
            "session_id": session_id,
            "message_length": len(message),
            # "has_image": image is not None,  # 云侧不再接收图像
            "request_id": request_id,
        },
    )

    emobot_logger.log_api_request(
        "POST",
        "/api/conversation/interact",
        {
            "user_id": user_id,
            "session_id": session_id,
            "message_length": len(message),
            # "has_image": image is not None,  # 云侧不再接收图像
            "request_id": request_id,
        },
        user_id=user_id,
        session_id=session_id,
    )

    try:
        # 步骤1: 初始化服务
        with track_step("INITIALIZE_SERVICES", {"user_id": user_id, "session_id": session_id}):
            conversation_service = ConversationService(db)
            # 人脸识别功能已注释，云侧不再进行人脸识别
            # face_recognition_service = FaceRecognitionService()

        logger.info(
            f"Processing interact request - user_id: {user_id}, session_id: {session_id}, message_length: {len(message)}"
        )

        # 步骤2: 处理图片上传和人脸识别（已注释，云侧不再接收图像数据）
        # image_url = None
        detected_user_id = user_id
        # face_recognition_result = None

        # if image:
        #     # 图片上传到OBS
        #     with track_step("IMAGE_UPLOAD", {"filename": image.filename, "size": image.size}):
        #         try:
        #             if not user_id:
        #                 # write image to local with no user id
        #                 local_image_path = image_manager.get_full_path(
        #                     image_manager.generate_unique_filename(image.filename or "")
        #                 )
        #                 with open(local_image_path, "wb") as f:
        #                     f.write(await image.read())
        #                 # 重置指针，保证后续还能读
        #                 image.file.seek(0)
        # 
        #             # OBS上传已注释 - 使用本地存储
        #             # upload_start = time.time()
        #             # image_url = upload_to_obs(
        #             #     image.file, image.filename or "image.jpg", "conversation_images"
        #             # )
        #             # upload_duration = (time.time() - upload_start) * 1000
        #             
        #             # 使用本地存储替代OBS
        #             upload_start = time.time()
        #             image_url = image_manager.save_image(image.file, image.filename or "image.jpg")
        #             upload_duration = (time.time() - upload_start) * 1000
        # 
        #             # 记录本地存储上传详情
        #             log_data_transfer(
        #                 transfer_type="UPLOAD_LOCAL",
        #                 data_size=image.size or 0,
        #                 duration_ms=upload_duration,
        #                 source="client",
        #                 destination="local://conversation_images"
        #             )
        # 
        #             logger.info(f"Image uploaded successfully: {image_url}")
        #         except Exception as e:
        #             logger.error(f"Failed to upload image: {e}")
        #             emobot_logger.log_face_operation("image_save_error", error=str(e))
        #             performance_tracker.end_request(error=f"Image upload failed: {str(e)}")
        #             return {"error": "Failed to upload image"}

        # 步骤3: 人脸识别处理（已注释，云侧不再进行人脸识别）
        # if not user_id and image:
        #     logger.info("No user_id provided, attempting face recognition")
        #     emobot_logger.log_face_operation("face_recognition_attempt")
        #
        #     # 人脸识别处理
        #     with track_step("FACE_RECOGNITION", {"image_path": local_image_path}):
        #         try:
        #             face_start = time.time()
        #             face_recognition_result = (
        #                 face_recognition_service.process_image_for_face_recognition(
        #                     db, local_image_path
        #                 )
        #             )
        #             face_duration = (time.time() - face_start) * 1000
        #
        #             # 记录人脸识别API调用
        #             log_api_call(
        #                 api_name="FACE_RECOGNITION",
        #                 api_type="FACE_RECOGNITION",
        #                 request_data={"image_path": local_image_path},
        #                 response_data=face_recognition_result,
        #                 duration_ms=face_duration
        #             )
        #
        #             if face_recognition_result and face_recognition_result.get(
        #                     "face_detected"
        #             ):
        #                 detected_user_id = face_recognition_result.get("user_id")
        #                 confidence = face_recognition_result.get("confidence", 0)
        #
        #                 logger.info(
        #                     f"Face recognition result: detected_user_id={detected_user_id}, confidence={confidence}"
        #                 )
        #                 emobot_logger.log_face_operation(
        #                     "face_recognized", detected_user_id, confidence
        #                 )
        #             else:
        #                 logger.info("No face detected in image")
        #                 emobot_logger.log_face_operation("no_face_detected")
        #
        #         except Exception as e:
        #             logger.error(f"Face recognition error: {e}")
        #             emobot_logger.log_face_operation("face_recognition_error", error=str(e))
        #             log_api_call(
        #                 api_name="FACE_RECOGNITION",
        #                 api_type="FACE_RECOGNITION",
        #                 request_data={"image_path": local_image_path},
        #                 error=str(e)
        #             )

        # If no user_id provided and no face detected, return error
        if not detected_user_id and not session_id:
            error_msg = "No user identification available. Please provide user_id or upload an image with a detectable face."
            logger.warning(error_msg)
            result = {
                "error": error_msg,
                # "face_recognition_result": face_recognition_result,  # 云侧不再进行人脸识别
            }
            duration = (time.time() - start_time) * 1000
            emobot_logger.log_api_response(
                "POST", "/api/conversation/interact", 400, result, duration
            )
            return result

        # 支持访客模式：允许没有用户档案的用户进行对话
        user_service = UserService(db)
        user_profile = user_service.get_user_profile(detected_user_id or user_id)
        is_guest_mode = user_profile is None
        
        if is_guest_mode:
            logger.info(f"User profile not found for user {detected_user_id or user_id}, entering guest mode")

        # If no session_id provided, start a new conversation
        if not session_id:
            session_id = conversation_service.start_conversation(detected_user_id)
            logger.info(
                f"Started new conversation for user {detected_user_id} with session {session_id}"
            )

        # 步骤4: 处理对话消息
        logger.info(
            f"Processing message for user {detected_user_id or user_id}, session {session_id}"
        )

        # env_context 已移除，不再使用

        with track_step("CONVERSATION_PROCESSING", {
            "user_id": detected_user_id or user_id,
            "session_id": session_id,
            "message_length": len(message),
        }):
            result = await conversation_service.process_message(
                detected_user_id or user_id, session_id, message  # image_url已移除
            )

        duration = (time.time() - start_time) * 1000
        logger.info(f"Interact request completed successfully in {duration:.2f}ms")
        emobot_logger.log_api_response(
            "POST", "/api/conversation/interact", 200, result, duration
        )
        log_function_result("interact", result, duration)

        # 结束性能追踪
        performance_tracker.end_request(response_data=result)

        return result

    except Exception as e:
        duration = (time.time() - start_time) * 1000
        logger.error(f"Interact request failed: {e}")
        log_function_error(
            "interact",
            e,
            {
                "user_id": user_id,
                "session_id": session_id,
                "message_length": len(message),
                # "has_image": image is not None,  # 云侧不再接收图像
            },
        )
        emobot_logger.log_api_response(
            "POST", "/api/conversation/interact", 500, {"error": str(e)}, duration
        )

        # 结束性能追踪（异常情况）
        performance_tracker.end_request(error=str(e))

        raise HTTPException(status_code=500, detail=str(e))


@router.post("/interact-stream")
async def interact_stream(
        user_id: Optional[str] = Form(None),
        session_id: Optional[str] = Form(None),
        message: str = Form(...),
        plane_description: Optional[str] = Form(None),
        environment_summary: Optional[str] = Form(None),
        robot_id: Optional[str] = Form(None),
        emotion: Optional[str] = Form(None),
        scene_familiarity: Optional[str] = Form(None),
        # image: Optional[UploadFile] = File(None),  # 云侧不再接收图像数据
        db: Session = Depends(get_db),
):
    """Send a message with streaming response"""
    start_time = time.time()
    log_function_call(
        "interact_stream",
        {
            "user_id": user_id,
            "session_id": session_id,
            "message_length": len(message),
            # "has_image": image is not None,  # 云侧不再接收图像
        },
    )

    emobot_logger.log_api_request(
        "POST",
        "/api/conversation/interact-stream",
        {
            "user_id": user_id,
            "session_id": session_id,
            "message_length": len(message),
            # "has_image": image is not None,  # 云侧不再接收图像
        },
        user_id=user_id,
        session_id=session_id,
    )

    try:
        # env_context 已移除，不再使用

        conversation_service = ConversationService(db)
        # 云侧人脸识别已禁用
        # face_recognition_service = FaceRecognitionService()

        logger.info(
            f"Processing interact-stream request - user_id: {user_id}, session_id: {session_id}, message_length: {len(message)}"
        )

        # Handle image upload (已注释，云侧不再接收图像数据)
        # image_url = None
        detected_user_id = user_id

        # if image:
        #     try:
        #         if not user_id:
        #             # write image to local with no user id
        #             local_image_path = image_manager.get_full_path(
        #                 image_manager.generate_unique_filename(image.filename or "")
        #             )
        #             with open(local_image_path, "wb") as f:
        #                 f.write(await image.read())
        #             # 重置指针，保证后续还能读
        #             image.file.seek(0)
        #         # OBS上传已注释 - 使用本地存储
        #         # image_url = upload_to_obs(
        #         #     image.file, image.filename or "image.jpg", "conversation_images"
        #         # )
        #         
        #         # 使用本地存储替代OBS
        #         image_url = image_manager.save_image(image.file, image.filename or "image.jpg")
        #         logger.info(f"Image uploaded successfully: {image_url}")
        #     except Exception as e:
        #         logger.error(f"Failed to upload image: {e}")
        #         emobot_logger.log_face_operation("image_save_error", error=str(e))
        #         return {"error": "Failed to upload image"}

        # 云侧人脸识别已禁用
        # if not user_id and image:
        #     logger.info("No user_id provided, attempting face recognition")
        #     emobot_logger.log_face_operation("face_recognition_attempt")
        #
        #     try:
        #         face_recognition_result = (
        #             face_recognition_service.process_image_for_face_recognition(
        #                 db, local_image_path
        #             )
        #         )
        #
        #         if face_recognition_result and face_recognition_result.get(
        #                 "face_detected"
        #         ):
        #             detected_user_id = face_recognition_result.get("user_id")
        #             confidence = face_recognition_result.get("confidence", 0)
        #
        #             logger.info(
        #                 f"Face recognition result: detected_user_id={detected_user_id}, confidence={confidence}"
        #             )
        #             emobot_logger.log_face_operation(
        #                 "face_recognized", detected_user_id, confidence
        #             )
        #         else:
        #             logger.info("No face detected in image")
        #             emobot_logger.log_face_operation("no_face_detected")
        #
        #     except Exception as e:
        #         logger.error(f"Face recognition error: {e}")
        #         emobot_logger.log_face_operation("face_recognition_error", error=str(e))

        # Check user identification
        if not detected_user_id and not session_id:
            error_msg = "No user identification available. Please provide user_id."
            logger.warning(error_msg)
            result = {
                "error": error_msg,
                # "face_recognition_result": face_recognition_result,  # 人脸识别已禁用
            }
            duration = (time.time() - start_time) * 1000
            emobot_logger.log_api_response(
                "POST", "/api/conversation/interact-stream", 400, result, duration
            )
            return result

        # 支持访客模式：允许没有用户档案的用户进行对话
        user_service = UserService(db)
        user_profile = user_service.get_user_profile(detected_user_id or user_id)
        is_guest_mode = user_profile is None
        
        if is_guest_mode:
            logger.info(f"User profile not found for user {detected_user_id or user_id}, entering guest mode")

        # Start new conversation if no session_id
        if not session_id:
            session_id = conversation_service.start_conversation(detected_user_id)
            logger.info(
                f"Started new conversation for user {detected_user_id} with session {session_id}"
            )

        # Process the message with streaming
        logger.info(
            f"Processing streaming message for user {detected_user_id or user_id}, session {session_id}"
        )

        # Get streaming generator from service
        stream_generator = conversation_service.process_message_streaming(
            detected_user_id or user_id, session_id, message  # image_url已移除
        )

        duration = time.time() - start_time
        logger.info(f"Interact-stream request setup completed in {duration:.2f}ms")

        return StreamingResponse(
            conversation_service.generate_sse_response(
                stream_generator, session_id, detected_user_id or user_id
            ),
            media_type="text/event-stream",
            headers={
                "Cache-Control": "no-cache",
                "Connection": "keep-alive",
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Headers": "*",
            },
        )

    except Exception as e:
        duration = (time.time() - start_time) * 1000
        logger.error(f"Interact-stream request failed: {e}")
        log_function_error(
            "interact_stream",
            e,
            {
                "user_id": user_id,
                "session_id": session_id,
                "message_length": len(message),
                # "has_image": image is not None,  # 云侧不再接收图像
            },
        )
        emobot_logger.log_api_response(
            "POST",
            "/api/conversation/interact-stream",
            500,
            {"error": str(e)},
            duration,
        )
        raise HTTPException(status_code=500, detail=str(e))


# 人脸识别功能已注释，云侧不再进行人脸识别
# @router.post("/register-face")
# def register_face(
#         user_id: str = Form(...),
#         image: UploadFile = File(...),
#         db: Session = Depends(get_db),
# ):
#     """Register a user's face for recognition"""
#     start_time = time.time()
#     log_function_call("register_face", {"user_id": user_id})
#     emobot_logger.log_api_request(
#         "POST", "/api/conversation/register-face", {"user_id": user_id}, user_id=user_id
#     )
#
#     try:
#         logger.info(f"Starting face registration for user {user_id}")
#         emobot_logger.log_face_operation("registration_start", user_id)
#
#         # OBS上传已注释 - 使用本地存储
#         # Save image using OBS upload
#         # image_url = upload_to_obs(
#         #     image.file, image.filename or "face_registration.jpg", "face_registration"
#         # )
#         
#         # 使用本地存储替代OBS
#         image_url = image_manager.save_image(image.file, image.filename or "face_registration.jpg")
#         logger.info(f"Image uploaded for face registration: {image_url}")
#
#         # Process image for face registration
#         face_recognition_service = FaceRecognitionService()
#
#         # Process image from URL for face detection
#         face_recognition_result = (
#             face_recognition_service.process_image_for_face_recognition(db, image_url)
#         )
#
#         if not face_recognition_result or not face_recognition_result.get(
#                 "face_detected"
#         ):
#             error_msg = "No face detected in image"
#             logger.warning(error_msg)
#             emobot_logger.log_face_operation("no_face_detected", user_id)
#             return {"error": error_msg}
#
#         # Get face embedding from the processed result
#         # Note: We need to modify the face recognition service to return the embedding
#         # For now, let's process the image again to get the embedding
#         face_embedding = face_recognition_service.get_face_embedding_from_url(image_url)
#
#         if face_embedding is None:
#             error_msg = "Could not generate face embedding"
#             logger.error(error_msg)
#             emobot_logger.log_face_operation(
#                 "embedding_failed", user_id, error=error_msg
#             )
#             return {"error": error_msg}
#
#         # Save face embedding to database
#         success = face_recognition_service.save_face_embedding(
#             db=db,
#             user_id=user_id,
#             face_embedding=face_embedding,
#             face_url=image_url,
#             face_image_path=image_url,
#             confidence_score=0.8,
#         )
#
#         if success:
#             result = {
#                 "message": "Face registered successfully",
#                 "user_id": user_id,
#                 "face_url": image_url,
#                 "embedding_dimension": len(face_embedding),
#             }
#             logger.info(f"Face registration successful for user {user_id}")
#             emobot_logger.log_face_operation("registration_success", user_id, 0.8)
#
#             duration = (time.time() - start_time) * 1000
#             emobot_logger.log_api_response(
#                 "POST", "/api/conversation/register-face", 200, result, duration
#             )
#             log_function_result("register_face", result, duration)
#
#             return result
#         else:
#             error_msg = "Failed to save face embedding to database"
#             logger.error(error_msg)
#             emobot_logger.log_face_operation("db_save_failed", user_id, error=error_msg)
#
#             duration = (time.time() - start_time) * 1000
#             emobot_logger.log_api_response(
#                 "POST",
#                 "/api/conversation/register-face",
#                 500,
#                 {"error": error_msg},
#                 duration,
#             )
#
#             return {"error": error_msg}
#
#     except Exception as e:
#         duration = (time.time() - start_time) * 1000
#         logger.error(f"Face registration error: {e}")
#         emobot_logger.log_face_operation(
#             "registration_exception", user_id, error=str(e)
#         )
#         log_function_error("register_face", e, {"user_id": user_id})
#         emobot_logger.log_api_response(
#             "POST", "/api/conversation/register-face", 500, {"error": str(e)}, duration
#         )
#         return {"error": f"Face registration failed: {str(e)}"}


@router.post("/end")
def end_conversation(
        user_id: str = Form(...), session_id: str = Form(...), db: Session = Depends(get_db)
):
    """End a conversation and trigger processing"""
    start_time = time.time()
    log_function_call(
        "end_conversation", {"user_id": user_id, "session_id": session_id}
    )
    emobot_logger.log_api_request(
        "POST",
        "/api/conversation/end",
        {"user_id": user_id, "session_id": session_id},
        user_id=user_id,
        session_id=session_id,
    )

    try:
        logger.info(f"Ending conversation for user {user_id}, session {session_id}")
        emobot_logger.log_conversation_event("end", user_id, session_id)

        # Trigger async task to process conversation end
        process_conversation_end.delay(user_id, session_id)
        logger.info(
            f"Background task started for conversation analysis - user: {user_id}, session: {session_id}"
        )

        result = {
            "message": "Conversation ended. Emotion and personality analysis will continue in the background.",
            "status": "processing",
            "user_id": user_id,
            "session_id": session_id,
            "note": "Check user profile later for analysis results",
        }

        duration = (time.time() - start_time) * 1000
        emobot_logger.log_api_response(
            "POST", "/api/conversation/end", 200, result, duration
        )
        log_function_result("end_conversation", result, duration)

        return result

    except Exception as e:
        duration = (time.time() - start_time) * 1000
        logger.error(f"Error ending conversation: {e}")
        log_function_error(
            "end_conversation", e, {"user_id": user_id, "session_id": session_id}
        )
        emobot_logger.log_api_response(
            "POST", "/api/conversation/end", 500, {"error": str(e)}, duration
        )
        raise HTTPException(status_code=500, detail=str(e))


# 反思检查端点已注释（反思模块已禁用）
# @router.post("/reflection/check")
# async def check_response_quality(
#     user_message: str = Form(...),
#     bot_response: str = Form(...),
#     db: Session = Depends(get_db)
# ):
#     """检查回复质量"""
#     start_time = time.time()
#     log_function_call("check_response_quality", {
#         "user_message_length": len(user_message),
#         "bot_response_length": len(bot_response)
#     })
#     
#     try:
#         reflection_service = ReflectionService(LLMService())
#         result = await reflection_service.reflect_on_response(user_message, bot_response)
#         
#         duration = (time.time() - start_time) * 1000
#         log_function_result("check_response_quality", result, duration)
#         
#         return {
#             "status": "success",
#             "reflection_result": result,
#             "duration_ms": duration
#         }
#     except Exception as e:
#         duration = (time.time() - start_time) * 1000
#         logger.error(f"反思检查失败: {e}")
#         log_function_error("check_response_quality", e, {
#             "user_message_length": len(user_message),
#             "bot_response_length": len(bot_response)
#         })
#         return {
#             "status": "error",
#             "message": str(e),
#             "duration_ms": duration
#         }


@router.get("/context/summary")
async def get_context_summary(
    user_id: str = Query(..., description="用户ID"),
    session_id: str = Query(..., description="会话ID"),
    db: Session = Depends(get_db)
):
    """获取上下文摘要"""
    start_time = time.time()
    log_function_call("get_context_summary", {
        "user_id": user_id,
        "session_id": session_id
    })
    
    try:
        from services.context_manager import ContextManager
        context_manager = ContextManager()
        
        summary = context_manager.get_context_summary(user_id, session_id)
        
        duration = (time.time() - start_time) * 1000
        log_function_result("get_context_summary", summary, duration)
        
        return {
            "status": "success",
            "context_summary": summary,
            "duration_ms": duration
        }
    except Exception as e:
        duration = (time.time() - start_time) * 1000
        logger.error(f"获取上下文摘要失败: {e}")
        log_function_error("get_context_summary", e, {
            "user_id": user_id,
            "session_id": session_id
        })
        return {
            "status": "error",
            "message": str(e),
            "duration_ms": duration
        }
